package com.uduemc.jcms.controller.jcms;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.uduemc.jcms.component.RepertoryUtil;
import com.uduemc.jcms.exception.NotFoundRepertoryException;
import com.uduemc.jcms.generate.entity.JcmsRepertory;
import com.uduemc.jcms.generate.service.IJcmsRepertoryService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;

@Controller
@RequestMapping("/jcms-source")
public class JcmsSourceController {

	@Autowired
	RepertoryUtil repertoryUtil;

	@Autowired
	IJcmsRepertoryService jcmsRepertoryServiceImpl;

	@GetMapping(value = "/upload/repertory/{year}/{month}/{day}/{imageName}")
	public void repertory(@PathVariable("year") String year, @PathVariable("month") String month, @PathVariable("day") String day,
			@PathVariable("imageName") String imageName, HttpServletResponse response) {

		String suffix = FileUtil.getSuffix(imageName);
		String unidname = StrUtil.removeSuffix(imageName, "." + suffix);
		JcmsRepertory jcmsRepertory = jcmsRepertoryServiceImpl.getByUnidname(unidname);
		if (jcmsRepertory == null) {
			// "资源文件不存在！"
			throw new NotFoundRepertoryException("资源文件不存在！", unidname);
		}

		String path = jcmsRepertory.getFilepath();
		String fullPath = repertoryUtil.getRepertoryFullPathByPath(path);
		File file = new File(fullPath);
		if (!file.isFile()) {
			// "资源文件不存在！"
			throw new NotFoundRepertoryException("资源文件不存在！ fullPath: " + fullPath, fullPath);
		}

		if (jcmsRepertory.getType().intValue() == RepertoryUtil.IMAGE) {
			imageResponse(response, fullPath, jcmsRepertory.getOriginalFilename(), jcmsRepertory.getSuffix());
		} else if (jcmsRepertory.getType().intValue() == RepertoryUtil.FILE) {
			if (jcmsRepertory.getSuffix().toUpperCase().equals("PDF")) {
				pdfResponse(response, fullPath, jcmsRepertory.getOriginalFilename());
			}
		} else if (jcmsRepertory.getType().intValue() == RepertoryUtil.VIDEO || jcmsRepertory.getType().intValue() == RepertoryUtil.AUDIO) {
			mediaResponse(response, fullPath, jcmsRepertory.getOriginalFilename(), jcmsRepertory.getType().intValue());
		}

	}

	/**
	 * 下载仓库资源接口
	 * 
	 * @param unidname
	 * @param response
	 * @throws Exception
	 */
	@GetMapping("/repertory/download.html")
	public void repertory(@RequestParam("unidname") String unidname, HttpServletResponse response) throws Exception {
		JcmsRepertory jcmsRepertory = jcmsRepertoryServiceImpl.getByUnidname(unidname);
		if (jcmsRepertory == null) {
			return;
		}

		String path = jcmsRepertory.getFilepath();
		String fullPath = repertoryUtil.getRepertoryFullPathByPath(path);
		if (!new File(fullPath).isFile()) {
			// "资源文件不存在！"
			throw new NotFoundRepertoryException("资源文件不存在！", fullPath, unidname);
		}
		// 下载
		try (InputStream inputStream = new FileInputStream(fullPath); OutputStream outputStream = response.getOutputStream();) {
			// response header
			response.setContentType("application/x-download");

			// 下载
			response.addHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode(jcmsRepertory.getOriginalFilename()));

			IoUtil.copy(inputStream, outputStream);
			outputStream.flush();
		}
	}

	protected void mediaResponse(HttpServletResponse response, String fullpath, String name, int repertoryType) {
		File file = new File(fullpath);
		try (OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(file);) {
			response.reset();
			if (repertoryType == RepertoryUtil.VIDEO) {
//				response.setContentType("video/mpeg4");
			} else if (repertoryType == RepertoryUtil.AUDIO) {
//				response.setContentType("audio/mp3");
			}
			response.setContentType("audio/mpeg");
			response.setHeader("Content-Disposition", "inline; filename=" + new String(name.getBytes(), "utf-8"));
			response.addHeader("Content-Length", "" + file.length());
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void pdfResponse(HttpServletResponse response, String pdfPath, String name) {
		File file = new File(pdfPath);
		try (OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(file);) {
			response.reset();
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "inline; filename=" + new String(name.getBytes(), "utf-8"));
			response.addHeader("Content-Length", "" + file.length());
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void imageResponse(HttpServletResponse response, String imagePath, String originalFilename, String suffix) {
		File file = new File(imagePath);
		try (OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(file);) {
			response.reset();
			response.setContentType("image/" + suffix);
			response.setHeader("Content-Disposition", "inline; filename=" + new String(originalFilename.getBytes(), "utf-8"));
			response.addHeader("Content-Length", "" + file.length());
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
